package cn.gene.timeyan.coo.webapi.service.impl;

import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.common.restful.JsonResult;
import cn.gene.timeyan.common.restful.ResponseCode;
import cn.gene.timeyan.coo.service.ApplyService;
import cn.gene.timeyan.coo.service.CooperationService;
import cn.gene.timeyan.coo.webapi.mapper.ApplyMapper;
import cn.gene.timeyan.coo.webapi.mapper.CooperationMapper;
import cn.gene.timeyan.pojo.coo.dto.ApplyByCooperationDTO;
import cn.gene.timeyan.pojo.coo.dto.ApplyDTO;
import cn.gene.timeyan.pojo.coo.model.Apply;
import cn.gene.timeyan.pojo.coo.vo.ApplyVO;
import cn.gene.timeyan.pojo.coo.vo.CooperationVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cn.gene.timeyan.common.restful.ResponseCode.INTERNAL_SERVER_ERROR;

/**
 * <p>
 * 浜掑姪鎻??璁板綍琛 服务实现类
 * </p>
 *IService<Apply>
 * @author LWG
 * @since 2022-07-25
 */
@Slf4j
@Service
public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements ApplyService {

    @Autowired(required = false)
    private ApplyMapper applyMapper;

    @Autowired(required = false)
    private CooperationMapper cooperationMapper;

    @Autowired
    private CooperationService cooperationService;


    @Override
    public void addApply(ApplyDTO applyDTO) {
        log.trace("业务逻辑层开始，开始处理vip业务");
        log.debug("尝试添加的求助揭榜信息：" + applyDTO);
        // 通过参数获取用户id
        log.trace("通过查看揭榜状态，判断此榜是否已经被别人揭了");


        //获取前端传递回来的对象
        ApplyByCooperationDTO cooperation = cooperationMapper.selectEndtimeAndApplyLimitByHelpId(applyDTO.getCooperationId());

        //通过cooperationId获取用户id
        List<ApplyVO> applyVOS = applyMapper.selectUserIdByCooperationId(applyDTO.getCooperationId(),applyDTO.getUserId());


        Integer applyLimit = cooperation.getApplyLimit();
        log.trace("最大揭榜人数:{}",applyLimit);

        //查看结束时间
        Date endTime = cooperation.getEndTime();
        //查看已揭榜数
        log.trace("查看已揭榜数");
        Integer applyBelimit = cooperation.getApplyBelimit();
        //定义一个当前揭榜时间
        Date now = new Date();

        //如果大于揭榜上限，则不能揭榜，抛出异常
        if (applyBelimit >= applyLimit) {
           log.error("此榜已满员，请重新揭其他榜",applyBelimit);
           throw new TimeyanServiceException(INTERNAL_SERVER_ERROR,"揭榜失败，人员已满。请尝试揭其他榜！");
           //如果超过了结束时间，则不能揭榜，抛出异常
        }else if (now.after(endTime)){
            log.error("此榜已过期，请重新揭其他榜",now);
            throw new TimeyanServiceException(INTERNAL_SERVER_ERROR,"揭榜失败，榜单已过期。请尝试揭其他榜！");

        }
        //同一个人不能揭同一个榜
        else if (applyVOS.size()>0) {//说明这个人已经揭了这个榜了
            throw new TimeyanServiceException(INTERNAL_SERVER_ERROR,"揭榜失败，您已揭过此榜，请尽快完成任务！");
        }

        // 日志
        log.trace("此求助榜未被揭，准备向表中写入此次添加的揭榜用户信息");

        // 创建对象
       Apply apply = new Apply();

        // 补全VIP对象的属性值
        BeanUtils.copyProperties(applyDTO, apply);
        apply.setApplyTime(now);
        apply.setCreateTime(now);
        apply.setUpdateTime(now);

        //添加数据
        int rows = applyMapper.insert(apply);

        //判断结果是否为1
        if (rows != 1) {
            throw new TimeyanServiceException(INTERNAL_SERVER_ERROR,"添加揭榜用户失败，服务器忙，请稍后再次尝试！");
        }
        cooperationService.updateApplyBelimit(applyDTO.getCooperationId());
    }

    @Override
    public JsonResult<List<CooperationVO>> userNotFinishedList(Long userId, Integer page) {
        //判断参数正确与否
        if (userId==null||page==null||page<1){
            throw new TimeyanServiceException(ResponseCode.ERR_NOTIME,"系统繁忙");
        }
        //查询该用户发表的分享信息
        //查询30个
        PageHelper.startPage(page,30);
        List<Long> applyIds=applyMapper.getNotFinishedListByUserId(userId);
        if (applyIds==null ||applyIds.size()==0){
            throw new TimeyanServiceException(ResponseCode.ERR_NOTIME,"系统繁忙");
        }
        //获取互助信息
        List<CooperationVO> list=new ArrayList<>();
        for (Long cooperationId:applyIds) {
            CooperationVO coo=cooperationMapper.getHelpNoFinishByHelpId(cooperationId);
            if (coo!=null){
                list.add(coo);
            }
        }
        return JsonResult.ok(list);
    }
}
